package viewbuilder.java;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
public class HtmlBacker implements InvocationHandler {

    private StringBuffer sb;

    public HtmlBacker() {
        sb = new StringBuffer();
    }

    protected void write() {

    }

    public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable {
        boolean attributesSpecified = false;

        HtmlNode thisNode = new HtmlNode();
        if ( method.getName().equals( "text" ) ) {
            thisNode.text = (String) args[0];
        } else {
            thisNode.nodeName = method.getName();
            attributesSpecified = handleAttributes( args[0], thisNode );
            if ( attributesSpecified ) {
                addChildren( args[1], thisNode );
            } else {
                addChildren( args[0], thisNode );
            }
        }

        return thisNode;
    }

    private void addChildren( Object children, HtmlNode htmlNode ) {
        if ( children instanceof HtmlNode[] ) {
            htmlNode.children = extractChildren( (HtmlNode[]) children );
        } else {
            throw new IllegalArgumentException( "The children must be of type HtmlNode" );
        }
    }

    private List<HtmlNode> extractChildren(HtmlNode[] children) {
        List<HtmlNode> realChildren = new ArrayList<HtmlNode>();
        realChildren.addAll( Arrays.asList( children ) );
        return realChildren;
    }

    private boolean handleAttributes( Object attrs, HtmlNode htmlNode ) {
        if ( attrs instanceof List ) {
            htmlNode.attributes = (List<HtmlAttribute>) attrs;
            return true;
        }
        return false;
    }
}
